package com.awspaas.user.apps.processforsap.web;

import com.actionsoft.bpms.bo.engine.BO;
import com.actionsoft.bpms.commons.database.RowMap;
import com.actionsoft.bpms.commons.mvc.view.ResponseObject;
import com.actionsoft.bpms.server.UserContext;
import com.actionsoft.bpms.server.bind.annotation.Controller;
import com.actionsoft.bpms.server.bind.annotation.Mapping;
import com.actionsoft.bpms.util.DBSql;
import com.actionsoft.exception.BPMNError;
import com.actionsoft.sdk.local.SDK;
import com.actionsoft.sdk.local.api.cc.RDSAPI;
import com.actionsoft.sdk.local.api.cc.http.Response;
import com.alibaba.fastjson.JSONObject;
import com.alipay.sofa.common.profile.StringUtil;
import com.awspaas.user.apps.processforsap.util.WLUtil;
import net.sf.cglib.asm.$AnnotationVisitor;
import org.apache.commons.lang3.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

@Controller
public class SapController {
    @Mapping(value = "sap.dataforwl")
    public ResponseObject getWLData(UserContext userContext, String bindId) {
        return getData(userContext.getUID(),bindId);
    }

    public ResponseObject getData(String uid,String bindId){
        String arrs[] = {"BTCLGA", "hybrid BGA", "FCBGA", "FCCSP", "BUMP", "CP", "WLCCSP"};
        //获取基础信息表数据
        ResponseObject responseObject = ResponseObject.newOkResponse("数据处理成功");
        String rdsId = SDK.getRuleAPI().executeAtScript("@getSapParamas(SAP_MID_ID)");
        RDSAPI rdsapi = SDK.getCCAPI().getRDSAPI(rdsId);

        try {
            WLUtil wlUtil = new WLUtil();
            BO mainBo = SDK.getBOAPI().query("BO_EU_SAP_WLZSJ").detailByBindId(bindId);
            boolean isNeedWl = false;
            String wlbm = "";
            /**
             * 判断委外方式，并赋值工厂
             */
            String outWay = mainBo.getString("OUTWAY");
            //判断委外方式
            List<BO> jcstList = SDK.getBOAPI().query("BO_EU_SAP_JBST").bindId(bindId).list();

            //处理币种
            String sql111 = "select * from SAP_CUSTOMER_SALES where KUNNR='" + jcstList.get(0).getString("PAGEFORMAT") + "'";
            RowMap rowMap111 = rdsapi.getMap(sql111);
            if (rowMap111 != null) {
                mainBo.set("CURRENCY", rowMap111.getString("WAERS"));
                SDK.getBOAPI().update("BO_EU_SAP_WLZSJ", mainBo);
            }else{
                mainBo.set("CURRENCY", "CNY");
                SDK.getBOAPI().update("BO_EU_SAP_WLZSJ", mainBo);
            }

            wlUtil.createLod("------------------开始判断币种--------------------");
            String logInfo = "用户填入基础数据中，客户三码为"+jcstList.get(0).getString("PAGEFORMAT")+",查出此客户币种为"+mainBo.getString("CURRENCY");
            wlUtil.createLod(logInfo);


            if (jcstList.size() > 0) {
                wlUtil.createLod("------------------开始判断物料特性生成逻辑--------------------");
                //物料类型
                BO bo111 = jcstList.get(0);
                String matlGroup1111 = bo111.getString("MATL_GROUP");
                String matlType = bo111.getString("MATL_TYPE");
                //根据物料组生成不同数据
                String boName = "";
                //新物料特性生成逻辑
                if ("FERT".equals(matlType) || "HALB".equals(matlType)) {
                    boName = "BO_EU_SAP_CPWLL";
                    wlUtil.createLod("用户填入基础数据中，物料特性为FERT/HALB,开始创建物料特性-产品物料类数据");
                }  else if ("Z001/Z002/Z005/ROH".contains(matlType)) {
                    wlUtil.createLod("用户填入基础数据中，物料特性为Z001/Z005;");
                    if (matlGroup1111.startsWith("1-WF")) {
                        boName = "BO_EU_SAP_WAFER";
                        wlUtil.createLod("涉及物料组为1-WF开头,开始创建物料特性-Wafer and IC_Z_WAFER_MAT数据");
                    }else if ("1-IC-00".equals(matlGroup1111)||"1-IC-E0".equals(matlGroup1111)){
                        boName = "BO_EU_SAP_CPWLL";
                        wlUtil.createLod("涉及物料组非1-WF开头,开始创建物料特性-直材或间材数据");
                    }else {
                        boName = "BO_EU_SAP_ZCHJCH";
                        wlUtil.createLod("涉及物料组非1-WF开头,开始创建物料特性-直材或间材数据");
                    }
                } else if ("Z003".equals(matlType)) {
                    boName = "BO_EU_SAP_ZCHJCH";
                    wlUtil.createLod("用户填入基础数据中，物料特性为Z003,开始创建物料特性-直材或间材数据");
                }else if ("Z006/DIEN/UNBW/ERSA/Z003/Z004".contains(matlType)){
                    boName = "BO_EU_SAP_ZCHJCH";
                }
                if (StringUtil.isNotEmpty(boName)) {
                    BO bo1 = SDK.getBOAPI().query(boName).detailByBindId(mainBo.getBindId());
                    String zassemtypeForWLTX = "";
                    if (bo1 != null) {
                        zassemtypeForWLTX = bo1.getString("ZASSEMTYPE");
                    }
                    String ztype = bo111.getString("BASIC_MATL");
                    bo1 = new BO();
                    if ("FERT/HALB/ROH/Z006/DIEN/UNBW/ERSA/Z003/Z004".contains(matlType)){
                        bo1.set("ZFIFO","2");
                    }
                    bo1.set("ZCUSTOMCODE", bo111.getString("PAGEFORMAT"));
                    bo1.set("ZCUSTOMER", bo111.getString("PAGEFORMAT"));
                    wlUtil.createLod("自动带入客户三码："+bo111.getString("PAGEFORMAT"));
                    bo1.set("DEVICE", bo111.getString("BASIC_MATL"));
                    wlUtil.createLod("自动带入产品型号："+bo111.getString("BASIC_MATL"));
                    bo1.set("ZASSEMTYPE", bo111.getString("ZASSEMTYPE"));
                    wlUtil.createLod("自动带入封测类型："+bo111.getString("ZASSEMTYPE"));
                    bo1.set("ZMATTYPE", bo111.getString("BASIC_MATL"));
                    if (matlGroup1111.startsWith("1-IC-0")) {
                        bo1.set("Z_WAFER_MAT", "");
                        bo1.set("DEVICE", "");
                        bo1.set("ZASSEMTYPE", "");
                        wlUtil.createLod("由于物料组为1-IC-0开头，根据规则，不启用Wafer and IC_Z_WAFER_MAT视图");
                    }

                    //处理物料特性
                    if ("BO_EU_SAP_WAFER".equals(boName)) {
                        //如果填了型号，对型号的特殊值进行处理
                        String newValue = ztype.replace("\\", "-")
                                .replace("/", "-")
                                .replace(":", "-")
                                .replace("*", "-")
                                .replace("?", "-")
                                .replace("\"", "-")
                                .replace("<", "-")
                                .replace(">", "-")
                                .replace("|", "-");

                        if (!ztype.equals(newValue)) {
                            bo1.set("ZIMPTYPE", ztype);
                            bo1.set("ZTYPE", newValue);
                            wlUtil.createLod("物料特性特殊值处理，将型号的特殊值替换成-并同步型号");
                        }
                    } else if ("BO_EU_SAP_CPWLL".equals(boName)) {
                        String zassemtype = bo111.getString("ZASSEMTYPE");
                        if (StringUtil.isEmpty(zassemtype)) {
                            //判断物料特性是否有值，有的话带过来
                            if (bo1 != null) {
                                if (StringUtil.isNotEmpty(zassemtypeForWLTX)) {
                                    bo1.set("ZASSEMTYPE", zassemtypeForWLTX);
                                    for (BO jcstFortx : jcstList) {
                                        jcstFortx.set("ZASSEMTYPE", zassemtypeForWLTX);
                                        SDK.getBOAPI().update("BO_EU_SAP_JBST", jcstFortx);
                                    }
                                }
                            }
                        }
                    }else if ("BO_EU_SAP_ZCHJCH".equals(boName)){
                        if (!"FERT/HALB".contains(matlType)){
                            bo1.set("ZMATNAME",bo111.getString("WLMC"));
                            bo1.set("ZTYPE",bo111.getString("BASIC_MATL"));
                            bo1.set("ZSPEC",bo111.getString("GG"));
                        }
                    }

                    SDK.getBOAPI().removeByBindId("BO_EU_SAP_CPWLL", mainBo.getBindId());
                    SDK.getBOAPI().removeByBindId("BO_EU_SAP_WAFER", mainBo.getBindId());
                    SDK.getBOAPI().removeByBindId("BO_EU_SAP_ZCHJCH", mainBo.getBindId());
                    SDK.getBOAPI().create(boName, bo1, mainBo.getBindId(), uid);
                    wlUtil.createLod("物料特性数据同步完成！");

                }
            }




            if (jcstList != null && jcstList.size() > 0) {
                //物料类型
                BO bo = jcstList.stream().filter(bo1 -> StringUtil.isEmpty(bo1.getString("ISXGKC"))).collect(Collectors.toList()).get(0);
                String matlGroup = bo.getString("MATL_GROUP");
                String matlType = bo.getString("MATL_TYPE");
                //客户三码
                String pageformat = bo.getString("PAGEFORMAT");
                //产品型号
                String basicMatl = bo.getString("BASIC_MATL");

                if (matlType.equals("FERT") || matlType.equals("HALB")) {
                    wlUtil.createLod("用户填写基础数据物料类型为FERT/HABL,开始根据客户三码、封测类型、产品型号组合判断委外信息");
                    //获取客户三码、产品型号、封测类型
                    String sql = "select * from BO_EU_SAP_CPWLL where BINDID='" + mainBo.getBindId() + "'";
                    RowMap rowMap = DBSql.getMap(sql);

                    if (rowMap != null) {
                        String zassemtype = bo.getString("ZASSEMTYPE");
                        if (StringUtil.isNotEmpty(zassemtype) && (Arrays.stream(arrs).anyMatch(str -> str.equals(zassemtype)))) {
                            //查PO，PO有数据，则委外方式就是PO，如果PO没数据，则查STO，如果PO和STO都没数据，那就不是委外，如果都有数据，就是PO
                            String po = "select * from CRM_PC_MAINTAINPO where CUSTCODE='" + pageformat + "' and PKG='" + zassemtype + "' and (CUSTDEV='" + basicMatl + "' or CUSTDEV='ALL') and dr=0";
                            String sto = "select * from bd_defdoc where dr=0  and PK_DEFDOCLIST='1001G1100000004Y5P9D' and DEF1='" + pageformat + "' and def2 ='" + zassemtype + "' and Def4='" + basicMatl + "' and ENABLESTATE=2";
                            RowMap rowMap1 = rdsapi.getMap(po);
                            RowMap rowMap2 = rdsapi.getMap(sto);
                            if (rowMap1 != null && !matlGroup.equals("V-FO-00")) {
                                outWay = "PO";
                                wlUtil.createLod("获取到委外信息：PO");
                            } else if (rowMap2 != null) {
                                outWay = "STO";
                                wlUtil.createLod("获取到委外信息：STO");
                            }else{
                                wlUtil.createLod("未获取到委外信息，判定为非委外");
                            }
                        }
                    }

                    mainBo.set("OUTWAY", outWay);
                    //更新主表
                    SDK.getBOAPI().update("BO_EU_SAP_WLZSJ", mainBo);
                }
            }


            List<BO> listTK = jcstList.stream().filter(bo -> "V-TK-00".equals(bo.getString("MATL_GROUP"))).collect(Collectors.toList());
            List<BO> listAO11 = jcstList.stream().filter(bo -> "V-AO-00".equals(bo.getString("MATL_GROUP"))).collect(Collectors.toList());

            if (listTK != null && listTK.size() > 0) {
                //TK为主
                BO bo = listTK.stream().filter(bo1 -> StringUtil.isEmpty(bo1.getString("ISXGKC"))).collect(Collectors.toList()).get(0);
                String plant = jcstList.get(0).getString("PLANT");
                if (StringUtil.isNotEmpty(outWay)) {
                    BO bo1 = new BO();
                    //进行拆分
                    bo1.set("PLANT", plant.equals("FH00") ? "FS00" : "FH00");
                    bo1.set("IND_SECTOR", bo.getString("IND_SECTOR"));
                    bo1.set("BASIC_VIEW", bo.getString("BASIC_VIEW"));
                    bo1.set("LANGU", bo.getString("LANGU"));
                    bo1.set("AVAILCHECK", bo.getString("AVAILCHECK"));
                    bo1.set("MATL_TYPE", bo.getString("MATL_TYPE"));
                    bo1.set("OLD_MAT_NO", bo.getString("OLD_MAT_NO"));
                    bo1.set("MATERIAL", bo.getString("MATERIAL"));
                    bo1.set("MATL_DESC", bo.getString("MATL_DESC"));
                    bo1.set("TEXT_LINE", bo.getString("TEXT_LINE"));
                    bo1.set("BASE_UOM", bo.getString("BASE_UOM"));
                    bo1.set("MATL_GROUP", bo.getString("MATL_GROUP"));
                    bo1.set("PROD_HIER", bo.getString("PROD_HIER"));
                    bo1.set("SIZE_DIM", bo.getString("SIZE_DIM"));
                    bo1.set("BASIC_MATL", bo.getString("BASIC_MATL"));
                    bo1.set("PAGEFORMAT", bo.getString("PAGEFORMAT"));
                    bo1.set("PROD_MEMO", bo.getString("PROD_MEMO"));
                    bo1.set("WLMC", bo.getString("WLMC"));
                    bo1.set("ZASSEMTYPE", bo.getString("ZASSEMTYPE"));

                    System.out.println("----------outWay2:"+outWay);
                    List<BO> listCheck = jcstList.stream().filter(boPlant -> "FH00".equals(boPlant.getString("PLANT")) || "FS00".equals(boPlant.getString("PLANT"))).collect(Collectors.toList());
                    if (listCheck.size() >= 2) {

                    } else {
                        SDK.getBOAPI().create("BO_EU_SAP_JBST", bo1, bindId, uid);

                    }
                }
            } else if (listAO11 != null && listAO11.size() > 0) {
                //AO为主
                BO bo = listAO11.stream().filter(bo1 -> StringUtil.isEmpty(bo1.getString("ISXGKC"))).collect(Collectors.toList()).get(0);
                String plant = bo.getString("PLANT");
                if (StringUtil.isNotEmpty(outWay)) {
                    BO bo1 = new BO();
                    //进行拆分
                    bo1.set("PLANT", plant.equals("FH00") ? "FS00" : "FH00");
                    bo1.set("IND_SECTOR", bo.getString("IND_SECTOR"));
                    bo1.set("BASIC_VIEW", bo.getString("BASIC_VIEW"));
                    bo1.set("LANGU", bo.getString("LANGU"));
                    bo1.set("AVAILCHECK", bo.getString("AVAILCHECK"));
                    bo1.set("MATL_TYPE", bo.getString("MATL_TYPE"));
                    bo1.set("OLD_MAT_NO", bo.getString("OLD_MAT_NO"));
                    bo1.set("MATERIAL", bo.getString("MATERIAL"));
                    bo1.set("MATL_DESC", bo.getString("MATL_DESC"));
                    bo1.set("TEXT_LINE", bo.getString("TEXT_LINE"));
                    bo1.set("BASE_UOM", bo.getString("BASE_UOM"));
                    bo1.set("MATL_GROUP", bo.getString("MATL_GROUP"));
                    bo1.set("PROD_HIER", bo.getString("PROD_HIER"));
                    bo1.set("SIZE_DIM", bo.getString("SIZE_DIM"));
                    bo1.set("BASIC_MATL", bo.getString("BASIC_MATL"));
                    bo1.set("PAGEFORMAT", bo.getString("PAGEFORMAT"));
                    bo1.set("PROD_MEMO", bo.getString("PROD_MEMO"));
                    List<BO> listCheck = jcstList.stream().filter(boPlant -> "FH00".equals(bo1.getString("PLANT")) || "FS00".equals(bo1.getString("PLANT"))).collect(Collectors.toList());
                    if (listCheck.size() >= 2) {

                    } else {
                        SDK.getBOAPI().create("BO_EU_SAP_JBST", bo1, mainBo.getBindId(), uid);

                    }
                }
            } else {
                if (jcstList != null && jcstList.size() > 0) {
                    BO bo = jcstList.stream().filter(bo1 -> StringUtil.isEmpty(bo1.getString("ISXGKC"))).collect(Collectors.toList()).get(0);
                    String plant = bo.getString("PLANT");
                    if (StringUtil.isNotEmpty(outWay)) {
                        BO bo1 = new BO();
                        //进行拆分
                        bo1.set("PLANT", plant.equals("FH00") ? "FS00" : "FH00");
                        bo1.set("IND_SECTOR", bo.getString("IND_SECTOR"));
                        bo1.set("BASIC_VIEW", bo.getString("BASIC_VIEW"));
                        bo1.set("LANGU", bo.getString("LANGU"));
                        bo1.set("AVAILCHECK", bo.getString("AVAILCHECK"));
                        bo1.set("MATL_TYPE", bo.getString("MATL_TYPE"));
                        bo1.set("OLD_MAT_NO", bo.getString("OLD_MAT_NO"));
                        bo1.set("MATERIAL", bo.getString("MATERIAL"));
                        bo1.set("MATL_DESC", bo.getString("MATL_DESC"));
                        bo1.set("TEXT_LINE", bo.getString("TEXT_LINE"));
                        bo1.set("BASE_UOM", bo.getString("BASE_UOM"));
                        bo1.set("MATL_GROUP", bo.getString("MATL_GROUP"));
                        bo1.set("PROD_HIER", bo.getString("PROD_HIER"));
                        bo1.set("SIZE_DIM", bo.getString("SIZE_DIM"));
                        bo1.set("BASIC_MATL", bo.getString("BASIC_MATL"));
                        bo1.set("PAGEFORMAT", bo.getString("PAGEFORMAT"));
                        bo1.set("PROD_MEMO", bo.getString("PROD_MEMO"));
                        List<BO> listCheck = jcstList.stream().filter(boPlant -> "FH00".equals(bo1.getString("PLANT")) || "FS00".equals(bo1.getString("PLANT"))).collect(Collectors.toList());
                        if (listCheck.size() >= 2) {

                        } else {
                            SDK.getBOAPI().create("BO_EU_SAP_JBST", bo1, mainBo.getBindId(), uid);
                        }
                    }
                }
            }


            /**
             * 数据处理
             */


            //基础视图里，SAP物料号，如果为空，则要根据规则自动生成，不过基础视图有多少行数据，都只生成一个物料号塞到不同行里面

            List<BO> pidList = SDK.getBOAPI().query("BO_EU_SAP_PID").bindId(bindId).list();
            jcstList = SDK.getBOAPI().query("BO_EU_SAP_JBST").bindId(bindId).list();
            for (BO bo : jcstList) {
                String pid = "";

                String material = bo.getString("MATERIAL");
                if (StringUtil.isEmpty(material)) {
                    isNeedWl = true;
                } else {
                    wlbm = material;
                    List<BO> list = pidList.stream().filter(bo1 -> bo1.getString("MATERIAL").equals(bo.getString("MATERIAL"))).collect(Collectors.toList());
                    if (list == null || list.size() == 0) {

                    } else {
                        pid = list.get(0).getString("PIDCB");
                    }
                }
                //处理财务视图
                //√
                wlUtil.createCCST(bo, bindId, uid);
                //√
                wlUtil.createCGST(bo, bindId, mainBo, uid);
                //√
                wlUtil.createFLST(bo, bindId, uid, mainBo);
                //√
                wlUtil.createGZJHST(bo, bindId, uid, mainBo, pid);
                wlUtil.createJCST(bo, mainBo, bindId);
                //√
                wlUtil.createMRPST(bo, bindId, uid, mainBo, pid);
                //√
                wlUtil.createXSST(bo, bindId, uid, mainBo);
                //√
                wlUtil.createCWST(bo, bindId, uid, mainBo, pid);
            }
            /**
             * 无价厂拆分
             */

            // 如果销售视图ITEM_CAT是Z100或Z200，并且对应基础视图中的物料类型包含FERT、HALB、ROH、Z001，Z002，则需要生产无价厂试图（需要COPY基础视图，FH00——>FH0Z,FS00——>FS0Z
            // ，分类视图，直接COPY
            // ；销售视图，直接COPY
            // ；采购视图，生成空表
            // ；存储视图，一般工厂视图默认X、批次管理默认X、批次标识默认X，其他为空
            // ；财务视图、MRP、工作计划，只生成行，但无值。）

            jcstList = SDK.getBOAPI().query("BO_EU_SAP_JBST").bindId(bindId).list();
            //如果有了无价厂，不再进行拆分
            List<BO> isHas = jcstList.stream().filter(bo -> StringUtil.isNotEmpty(bo.getString("ISXGKC"))).collect(Collectors.toList());
//            List<BO> isHasXG = jcstList.stream().filter(bo -> bo.getString("PLANT").equals("FT00")).collect(Collectors.toList());
//            if (isHas != null && isHas.size() > 0) {
//                isHas.addAll(isHasXG);
//            }
            for (BO bo : isHas) {
                String id = bo.getId();
                SDK.getBOAPI().remove("BO_EU_SAP_JBST", id);
                //删除其他数据
                String[] arraName = {"BO_EU_SAP_FLST", "BO_EU_SAP_XSST", "BO_EU_SAP_CGST", "BO_EU_SAP_CCST", "BO_EU_SAP_CWST", "BO_EU_SAP_MRP", "BO_EU_SAP_GZJH"};
                for (String girdBoName : arraName) {
                    List<BO> list = SDK.getBOAPI().query(girdBoName).addQuery("MAINID=", id).list();
                    for (BO bo1 : list) {
                        if (bo1 != null) {
                            String newId = bo1.getId();
                            SDK.getBOAPI().remove(girdBoName, newId);
                        }
                    }
                }
            }
            jcstList = SDK.getBOAPI().query("BO_EU_SAP_JBST").bindId(bindId).list();

            List<BO> resultjcstList = jcstList.stream().filter(bo -> StringUtil.isEmpty(bo.getString("ISXGKC"))).collect(Collectors.toList());
            //无价厂扩充逻辑（新）
            for (BO jcstBO1 : resultjcstList) {
                String matlType = jcstBO1.getString("MATL_TYPE");
                String matlGroup1 = jcstBO1.getString("MATL_GROUP");
                String plant = jcstBO1.getString("PLANT");
                System.out.println("------------plant:"+plant);
                String finalPlant = "";
                if (plant.equals("FH00")) {
                    finalPlant = "FH0Z";
                } else if (plant.equals("FS00")) {
                    finalPlant = "FS0Z";
                }
                System.out.println("------------finalPlant:"+finalPlant);
                if ("FERT/HALB/Z002/Z001/Z005".contains(matlType)) {
                    if (matlGroup1.equals("1-SM-00")) {

                    } else {
                        System.out.println("------------finalPlant:"+finalPlant);
                        createData(uid, finalPlant, resultjcstList, jcstBO1, mainBo, bindId, "0", pidList);
                    }
                }
                if ("ROH".equals(matlType)){
                    if (matlGroup1.startsWith("1-WF")||matlGroup1.startsWith("2-DM")) {
                        createData(uid, finalPlant, resultjcstList, jcstBO1, mainBo, bindId, "0", pidList);
                    }
                }
                //香港有价厂处理——若客户中，问候包含香港，则生成对应的有价厂信息FT00
                String sql = "select count(*) as count from SAP_CUSTOMER where KUNNR = ? and TITLE_LET like '%香港%'";
                int result = rdsapi.getInt(sql, jcstBO1.getString("PAGEFORMAT"));
                if (result > 0) {
                    if ("FERT/HALB".contains(matlType) && "FS00/FH00".contains(plant)) {
                        createData(uid, plant, resultjcstList, jcstBO1, mainBo, bindId, "1", pidList);
                    }
                    if ("Z001/Z005".contains(matlType) && "FS00/FH00".contains(plant)) {
                        createData(uid, plant, resultjcstList, jcstBO1, mainBo, bindId, "1", pidList);
                    }
                }
            }
            jcstList = SDK.getBOAPI().query("BO_EU_SAP_JBST").bindId(bindId).list();
            //处理物料数据
            if (isNeedWl) {
                if (jcstList.size() > 0) {
                    jcstList = SDK.getBOAPI().query("BO_EU_SAP_JBST").bindId(bindId).list();
                    List<BO> list = jcstList.stream().filter(bo -> StringUtils.isNotEmpty(bo.getString("MATERIAL"))).collect(Collectors.toList());
                    if (list != null && list.size() > 0) {
                        String material = list.get(0).getString("MATERIAL");
                        wlbm = material;
                    } else {
                        String at = "@sequence(" + jcstList.get(0).getString("MATL_GROUP") + ",7,0)";
                        String newWl = jcstList.get(0).getString("MATL_GROUP") + "-" + SDK.getRuleAPI().executeAtScript(at);
                        wlbm = newWl;
                    }
                    for (BO bo : jcstList) {
                        String material = bo.getString("MATERIAL");
                        if (StringUtil.isEmpty(material)) {
                            bo.set("MATERIAL", wlbm);
                            SDK.getBOAPI().update("BO_EU_SAP_JBST", bo);
                        }
                    }
                }
            }
            BO bo = SDK.getBOAPI().query("BO_EU_SAP_WLTX").detailByBindId(mainBo.getBindId());
            if (bo != null) {
                bo.set("MATNR", wlbm);
                SDK.getBOAPI().update("BO_EU_SAP_WLTX", bo);
            } else {
                bo = new BO();
                bo.set("MATNR", wlbm);
                SDK.getBOAPI().create("BO_EU_SAP_WLTX", bo, mainBo.getBindId(), uid);
            }
            //处理关务数据
            //币种
            String currency = mainBo.getString("CURRENCY");
            String processInstId = mainBo.getBindId();
            List<BO> list = SDK.getBOAPI().query("BO_EU_SAP_JBST").addQuery("BINDID=", processInstId).list();
            BO boGird = list.get(0);
            String matlGroup = boGird.getString("MATL_GROUP");
            String matlType = boGird.getString("MATL_TYPE");
            if (currency.equals("USD") && (matlGroup.equals("1-WF-00") || matlGroup.equals("1-IC-00") || matlGroup.equals("1-SB-00"))) {
                BO newBo = SDK.getBOAPI().query("BO_EU_MM_GW").bindId(mainBo.getBindId()).detail();
                if (newBo != null) {
                    newBo.set("KH", boGird.getString("PAGEFORMAT"));
                    newBo.set("GYS", boGird.getString("PAGEFORMAT"));
                    newBo.set("XH", boGird.getString("BASIC_MATL"));
                    newBo.set("BZ", currency);
                    if ("Z001/Z005".contains(matlType)) {
                        if (StringUtil.isEmpty(newBo.getString("LJ_YXDZ"))) {
                            String at1 = "";
                            if (matlGroup.contains("1-WF")) {
                                at1 = "LJW" + boGird.getString("PAGEFORMAT") + "@sequence(LJW" + boGird.getString("PAGEFORMAT") + ",4,0)";
                            }
                            if (matlGroup.contains("1-IC")) {
                                at1 = "LJP" + boGird.getString("PAGEFORMAT") + "@sequence(LJP" + boGird.getString("PAGEFORMAT") + ",4,0)";
                            }
                            if (matlGroup.contains("1-SB")) {
                                at1 = "LJS" + boGird.getString("PAGEFORMAT") + "@sequence(LJS" + boGird.getString("PAGEFORMAT") + ",4,0)";
                            }
                            String at1Value = SDK.getRuleAPI().executeAtScript(at1) + "B";
                            newBo.set("LJ_YXDZ", at1Value);
                        }
                        if (StringUtil.isEmpty(newBo.getString("LJ_BDT"))) {
                            String at2 = "";
                            if (matlGroup.contains("1-WF")) {
                                at2 = "BDTW" + boGird.getString("PAGEFORMAT") + "@sequence(BDTW" + boGird.getString("PAGEFORMAT") + ",4,0)";
                            }
                            if (matlGroup.contains("1-IC")) {
                                at2 = "BDTP" + boGird.getString("PAGEFORMAT") + "@sequence(BDTP" + boGird.getString("PAGEFORMAT") + ",4,0)";
                            }
                            if (matlGroup.contains("1-SB")) {
                                at2 = "BDTS" + boGird.getString("PAGEFORMAT") + "@sequence(BDTS" + boGird.getString("PAGEFORMAT") + ",4,0)";
                            }
                            String at2Value = SDK.getRuleAPI().executeAtScript(at2) + "B";
                            newBo.set("LJ_BDT", at2Value);
                        }
                    }
                    newBo.set("MATL_TYPE", boGird.getString("MATL_TYPE"));
                    newBo.set("PLANT", boGird.getString("PLANT"));
                    newBo.set("MATERIAL", boGird.getString("MATERIAL"));
                    newBo.set("MATL_DESC", boGird.getString("MATL_DESC"));
                    newBo.set("TEXT_LINE", boGird.getString("TEXT_LINE"));
                    newBo.set("BASE_UOM", boGird.getString("BASE_UOM"));
                    newBo.set("BASIC_MATL", boGird.getString("BASIC_MATL"));
                    newBo.set("PAGEFORMAT", boGird.getString("PAGEFORMAT"));
                    newBo.set("MATL_GROUP", boGird.getString("MATL_GROUP"));
                    SDK.getBOAPI().update("BO_EU_MM_GW", newBo);
                } else {
                    newBo = new BO();
                    newBo.set("KH", boGird.getString("PAGEFORMAT"));
                    newBo.set("GYS", boGird.getString("PAGEFORMAT"));
                    newBo.set("XH", boGird.getString("BASIC_MATL"));
                    newBo.set("BZ", currency);
                    if ("Z001/Z005".contains(matlType)) {
                        String at1 = "";
                        if (matlGroup.contains("1-WF")) {
                            at1 = "LJW" + boGird.getString("PAGEFORMAT") + "@sequence(LJW" + boGird.getString("PAGEFORMAT") + ",4,0)";
                        }
                        if (matlGroup.contains("1-IC")) {
                            at1 = "LJP" + boGird.getString("PAGEFORMAT") + "@sequence(LJP" + boGird.getString("PAGEFORMAT") + ",4,0)";
                        }
                        if (matlGroup.contains("1-SB")) {
                            at1 = "LJS" + boGird.getString("PAGEFORMAT") + "@sequence(LJS" + boGird.getString("PAGEFORMAT") + ",4,0)";
                        }
                        String at1Value = SDK.getRuleAPI().executeAtScript(at1) + "B";
                        newBo.set("LJ_YXDZ", at1Value);
                        String at2 = "";
                        if (matlGroup.contains("1-WF")) {
                            at2 = "BDTW" + boGird.getString("PAGEFORMAT") + "@sequence(BDTW" + boGird.getString("PAGEFORMAT") + ",4,0)";
                        }
                        if (matlGroup.contains("1-IC")) {
                            at2 = "BDTP" + boGird.getString("PAGEFORMAT") + "@sequence(BDTP" + boGird.getString("PAGEFORMAT") + ",4,0)";
                        }
                        if (matlGroup.contains("1-SB")) {
                            at2 = "BDTS" + boGird.getString("PAGEFORMAT") + "@sequence(BDTS" + boGird.getString("PAGEFORMAT") + ",4,0)";
                        }
                        String at2Value = SDK.getRuleAPI().executeAtScript(at2) + "B";
                        newBo.set("LJ_BDT", at2Value);
                    }
                    newBo.set("MATL_TYPE", boGird.getString("MATL_TYPE"));
                    newBo.set("PLANT", boGird.getString("PLANT"));
                    newBo.set("MATERIAL", boGird.getString("MATERIAL"));
                    newBo.set("MATL_DESC", boGird.getString("MATL_DESC"));
                    newBo.set("TEXT_LINE", boGird.getString("TEXT_LINE"));
                    newBo.set("BASE_UOM", boGird.getString("BASE_UOM"));
                    newBo.set("BASIC_MATL", boGird.getString("BASIC_MATL"));
                    newBo.set("PAGEFORMAT", boGird.getString("PAGEFORMAT"));
                    newBo.set("MATL_GROUP", boGird.getString("MATL_GROUP"));
                    SDK.getBOAPI().create("BO_EU_MM_GW", newBo, mainBo.getBindId(), uid);
                }
            }
            mainBo.set("ISSC", "1");
            SDK.getBOAPI().update("BO_EU_SAP_WLZSJ", mainBo);
            List<BO> jcstList111 = SDK.getBOAPI().query("BO_EU_SAP_JBST").bindId(bindId).list();
            for (BO bo1 : jcstList111) {
                bo1.set("STATUS", "");
                SDK.getBOAPI().update("BO_EU_SAP_JBST", bo1);
            }
            if (StringUtil.isNotEmpty(outWay)) {
                SDK.getBOAPI().removeByBindId("BO_EU_SAP_WWFS",bindId);
                List<BO> list1111 = jcstList.stream().filter(bo1 -> bo1.getString("MATL_GROUP").equals("V-AO-00")).collect(Collectors.toList());
                if (list1111 != null && list1111.size() > 0) {
                    BO wwBo = new BO();
                    wwBo.set("MATERIAL", list1111.get(0).getString("MATERIAL"));
                    wwBo.set("OUTWAY", outWay);
                    SDK.getBOAPI().create("BO_EU_SAP_WWFS", wwBo, bindId, uid);
                }
            }
        } catch (
                Exception e) {
            e.printStackTrace();
            responseObject = ResponseObject.newErrResponse(e.getMessage());
        } finally {
            return responseObject;
        }
    }
    public void createData(String uid, String plant,List<BO> jcstList, BO oldBo, BO mainBo, String bindId, String isXg, List<BO> list) {
        BO newBO = new BO();
        String newCOPYID = UUID.randomUUID().toString();
        newBO.setId(newCOPYID);
        newBO.set("IND_SECTOR", oldBo.getString("IND_SECTOR"));
        newBO.set("BASIC_VIEW", oldBo.getString("BASIC_VIEW"));
        newBO.set("LANGU", oldBo.getString("LANGU"));

        String matlType = oldBo.getString("MATL_TYPE");
        String matlGroup = oldBo.getString("MATL_GROUP");
        String isMc = mainBo.getString("IS_MC");
        newBO.set("PLANT", plant);
        oldBo.set("PLANT",plant);
        System.out.println("------------finalPlant:"+plant);
        if ("FERT/HALB".contains(matlType) && "1".equals(isXg)) {
            oldBo.set("PLANT", "FT00");
            newBO.set("PLANT", "FT00");
        }
        if (matlType.equals("FERT") || matlType.equals("HALB")) {
            if (plant.contains("Z")) {
                newBO.set("AVAILCHECK", "Z2");
            } else {
                newBO.set("AVAILCHECK", "02");
            }
        } else {
            if ("DIEN/Z001/Z002/Z005/ROH".contains(matlType)) {
                newBO.set("AVAILCHECK", "02");
            }
            if ("FH0Z/FS0Z/YJ00".contains(plant)) {
                newBO.set("AVAILCHECK", "Z2");
            }
            if ("ERSA/Z004/UNBW".contains(matlType)) {
                newBO.set("AVAILCHECK", "KP");
            }
            if ("1-WF-00/1-WF-03/2-DM-00/2-DM-01".contains(matlGroup)) {
                newBO.set("AVAILCHECK", "KP");
            }
            if ("1".equals(isMc)) {
                newBO.set("AVAILCHECK", "Z2");
            }
        }

        newBO.set("MATL_TYPE", oldBo.getString("MATL_TYPE"));
        newBO.set("OLD_MAT_NO", oldBo.getString("OLD_MAT_NO"));
        newBO.set("MATERIAL", oldBo.getString("MATERIAL"));
        newBO.set("MATL_DESC", oldBo.getString("MATL_DESC"));
        newBO.set("TEXT_LINE", oldBo.getString("TEXT_LINE"));
        newBO.set("BASE_UOM", oldBo.getString("BASE_UOM"));
        newBO.set("MATL_GROUP", oldBo.getString("MATL_GROUP"));
        newBO.set("PROD_HIER", oldBo.getString("PROD_HIER"));
        newBO.set("SIZE_DIM", oldBo.getString("SIZE_DIM"));
        newBO.set("BASIC_MATL", oldBo.getString("BASIC_MATL"));
        newBO.set("PAGEFORMAT", oldBo.getString("PAGEFORMAT"));
        newBO.set("PROD_MEMO", oldBo.getString("PROD_MEMO"));
        newBO.set("WLMC", oldBo.getString("WLMC"));
        newBO.set("ZASSEMTYPE", oldBo.getString("ZASSEMTYPE"));
        newBO.set("ISXGKC", isXg);
        System.out.println("------------finalPlant111:"+newBO.getString("PLANT"));
        SDK.getBOAPI().create("BO_EU_SAP_JBST", newBO, mainBo.getBindId(), uid);

        String pid = "";

        String material = oldBo.getString("MATERIAL");
        List<BO> list11 = list.stream().filter(bo1 -> bo1.getString("MATERIAL").equals(material)).collect(Collectors.toList());
        if (list11 == null || list11.size() == 0) {

        } else {
            pid = list11.get(0).getString("PIDCB");
        }
        oldBo.setId(newCOPYID);
        oldBo.set("ISXGKC", isXg);
        WLUtil wlUtil = new WLUtil();
        wlUtil.createFLST(oldBo, bindId, uid, mainBo);
        wlUtil.createXSST(oldBo, bindId, uid, mainBo);
        wlUtil.createCCST(oldBo, bindId, uid);
        wlUtil.createCGST(oldBo, bindId, mainBo, uid);
        wlUtil.createGZJHST(oldBo, bindId, uid, mainBo, pid);
        wlUtil.createJCST(oldBo, mainBo, bindId);
        wlUtil.createMRPST(oldBo, bindId, uid, mainBo, pid);
        wlUtil.createCWST(oldBo, bindId, uid, mainBo, pid);
    }


    @Mapping(value = "sap.dataforco")
    public ResponseObject getCOData(UserContext userContext, String bindId, String gsdm) {
        //获取基础信息表数据
        ResponseObject responseObject = ResponseObject.newOkResponse("数据查询成功");
        String rdsId = SDK.getRuleAPI().executeAtScript("@getSapParamas(SAP_MID_ID)");
        RDSAPI rdsapi = SDK.getCCAPI().getRDSAPI(rdsId);
        Map map = new HashMap();

        try {
            String uid = userContext.getUID();
            String sql = "SELECT " +
                    "        e.emp_no AS USERID, " +
                    "        pp.level_name AS PAGER, " +
                    "        e.post_name AS TITLE, " +
                    "        l.emp_no AS MANAGER, " +
                    "        e.NAME AS DISPLAYNAME, " +
                    "        e.work_email AS MAIL, " +
                    "        e.mobile AS MOBILE, " +
                    "        e.certificate_no AS IDCARDNO, " +
                    "        e.native_place AS CENSUS, " +
                    "        CASE WHEN e.sex = 1 THEN '男' ELSE '女' END AS SEX, " +
                    "        e.org_origin_id AS PK_DEPT, " +
                    "        CASE WHEN e.STATUS = 0 THEN '在职' ELSE '离职' END AS ENDFLAG  " +
                    "        FROM emp_info e " +
                    "        JOIN per_orgs p ON e.org_origin_id = p.origin_id " +
                    "        JOIN per_company c ON e.company_id = c.id " +
                    "        LEFT JOIN per_post pp ON e.post_origin_id = pp.origin_id  " +
                    "        AND pp.is_delete = 0  " +
                    "        AND pp.enable_date <= sysdate AND pp.unable_date > sysdate" +
                    "        LEFT JOIN emp_info l ON l.origin_id = e.leader_origin_id  " +
                    "        AND l.is_delete = 0  " +
                    "        AND l.audit_status IN ( 3, 5 )  " +
                    "        AND l.enable_date <= sysdate AND l.unable_date > sysdate" +
                    "        WHERE " +
                    "        p.enable_date <= sysdate AND ( p.unable_date > sysdate  " +
                    "        OR p.is_failure = 1  " +
                    "        )  " +
                    "        AND p.is_delete = 0  " +
                    "        AND p.audit_status IN ( 3, 5 )  " +
                    "        AND e.enable_date <= sysdate AND e.unable_date > sysdate  " +
                    "        AND e.is_delete = 0  " +
                    "        AND e.audit_status IN ( 3, 5 )  " +
                    "        AND e.STATUS != '-1' AND E.emp_no='" + uid + "'";
            RowMap rowMap = rdsapi.getMap(sql);
            if (rowMap != null) {
                String pkDept = rowMap.getString("PK_DEPT");


                String sql1 = "SELECT id,name,parent_id,code FROM per_orgs WHERE is_delete = 0 AND unable_date > sysdate AND enable_date <= sysdate AND ORIGIN_ID='" + pkDept + "'";
                RowMap rowMap1 = rdsapi.getMap(sql1);

                if (rowMap1 != null) {
                    String code = rowMap1.getString("CODE");
                    map.put("code", code);

                    String sql2 = "select * from SAP_CSKS where ABTEI='" + code + "' and BUKRS='" + gsdm + "'";
                    RowMap rowMap2 = rdsapi.getMap(sql2);
                    if (rowMap2 != null) {
                        String kostl = rowMap2.getString("KOSTL");
                        map.put("kostl", kostl);

                    }
                }

            }

            responseObject.put(map);
        } catch (
                Exception e) {
            e.printStackTrace();
            responseObject = ResponseObject.newErrResponse(e.getMessage());
        } finally {
            return responseObject;
        }
    }

    public void createGWForm(String uid, String bindId) {
        BO mainBo = SDK.getBOAPI().query("BO_EU_SAP_WLZSJ").detailByBindId(bindId);

        //币种
        String currency = mainBo.getString("CURRENCY");
        String processInstId = mainBo.getBindId();
        List<BO> list = SDK.getBOAPI().query("BO_EU_SAP_JBST").addQuery("BINDID=", processInstId).list();
        BO boGird = list.get(0);
        String matlGroup = boGird.getString("MATL_GROUP");
        if (currency.equals("USD")) {
            BO newBo = SDK.getBOAPI().query("BO_EU_MM_GW").bindId(mainBo.getBindId()).detail();
            if (newBo != null) {
                newBo.set("MATL_TYPE", boGird.getString("MATL_TYPE"));
//                newBo.set("IS_BG", isBg);
                newBo.set("KH", boGird.getString("PAGEFORMAT"));
                newBo.set("GYS", boGird.getString("PAGEFORMAT"));
                newBo.set("XH", boGird.getString("BASIC_MATL"));
                newBo.set("BZ", currency);
                newBo.set("PLANT", boGird.getString("PLANT"));
                newBo.set("MATERIAL", boGird.getString("MATERIAL"));
                newBo.set("MATL_DESC", boGird.getString("MATL_DESC"));
                newBo.set("TEXT_LINE", boGird.getString("TEXT_LINE"));
                newBo.set("BASE_UOM", boGird.getString("BASE_UOM"));
                newBo.set("BASIC_MATL", boGird.getString("BASIC_MATL"));
                newBo.set("PAGEFORMAT", boGird.getString("PAGEFORMAT"));
                newBo.set("MATL_GROUP", boGird.getString("MATL_GROUP"));
                SDK.getBOAPI().update("BO_EU_MM_GW", newBo);
            } else {
                newBo = new BO();
                newBo.set("KH", boGird.getString("PAGEFORMAT"));
                newBo.set("GYS", boGird.getString("PAGEFORMAT"));
                newBo.set("XH", boGird.getString("BASIC_MATL"));
//                newBo.set("IS_BG", isBg);
                newBo.set("BZ", currency);
                String at1 = "LJW" + boGird.getString("PAGEFORMAT") + "@sequence(LJW" + boGird.getString("PAGEFORMAT") + ",4,0)";
                newBo.set("LJ_YXDZ", SDK.getRuleAPI().executeAtScript(at1));
                String at2 = "BDTW" + boGird.getString("PAGEFORMAT") + "@sequence(BDTW" + boGird.getString("PAGEFORMAT") + ",4,0)";
                newBo.set("LJ_BDT", SDK.getRuleAPI().executeAtScript(at2));
                newBo.set("MATL_TYPE", boGird.getString("MATL_TYPE"));
                newBo.set("PLANT", boGird.getString("PLANT"));
                newBo.set("MATERIAL", boGird.getString("MATERIAL"));
                newBo.set("MATL_DESC", boGird.getString("MATL_DESC"));
                newBo.set("TEXT_LINE", boGird.getString("TEXT_LINE"));
                newBo.set("BASE_UOM", boGird.getString("BASE_UOM"));
                newBo.set("BASIC_MATL", boGird.getString("BASIC_MATL"));
                newBo.set("PAGEFORMAT", boGird.getString("PAGEFORMAT"));
                newBo.set("MATL_GROUP", boGird.getString("MATL_GROUP"));
                SDK.getBOAPI().create("BO_EU_MM_GW", newBo, mainBo.getBindId(), uid);
            }
        }
    }


    @Mapping(value = "ccqh.fordata")
    public ResponseObject getGYSData(UserContext userContext, String gys, String cgzz) {
        ResponseObject responseObject = ResponseObject.newOkResponse("查询成功");
        String rdsId = SDK.getRuleAPI().executeAtScript("@getSapParamas(SAP_MID_ID)");
        RDSAPI rdsapi = SDK.getCCAPI().getRDSAPI(rdsId);
        String sql = "select * from SAP_VENDOR_PUR where LIFNR='" + gys + "' and EKORG = '" + cgzz + "'";
        RowMap rowMap = rdsapi.getMap(sql);
        if (rowMap != null) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("FIELD0121", rowMap.getString("ZTERM"));
            jsonObject.put("FIELD0040", rowMap.getString("INCO1"));
            responseObject.setData(jsonObject);
        }
        return responseObject;
    }


    @Mapping(value = "sap.firefreshData")
    public ResponseObject firefreshdata(UserContext userContext, String bindid, String type, String value) {
        ResponseObject responseObject = ResponseObject.newOkResponse("查询成功");
        List<BO> list = SDK.getBOAPI().query("BO_EU_SAP_FIZCLIST").bindId(bindid).list();
        for (BO bo : list) {
            bo.set(type, value);
            SDK.getBOAPI().update("BO_EU_SAP_FIZCLIST", bo);
        }
        return responseObject;
    }

    @Mapping(value = "ccqh.forCreateData")
    public ResponseObject createData(UserContext userContext, String bindid) {
        ResponseObject responseObject = ResponseObject.newOkResponse("查询成功");
        List<BO> list = SDK.getBOAPI().query("BO_EU_SAP_MM004GIRD2").bindId(bindid).list();
        SDK.getBOAPI().removeByBindId("BO_EU_SAP_MM004GIRD1", bindid);
        for (BO bo : list) {
            BO bo1 = new BO();
            bo1.set("FIELD0074", bo.getString("FIELD0052"));
            bo1.set("HH", bo.getString("FIELD0045"));
            SDK.getBOAPI().create("BO_EU_SAP_MM004GIRD1", bo1, bindid, userContext.getUID());
        }
        return responseObject;
    }
}
